//
//  MYGPatientListDetailViewController.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/4/18.
//

import UIKit
import JXSegmentedView

class MYGPatientListDetailViewController: MYGBaseController {
    var patientArr:[String:[MYGMyPatientModel]] = [:]
    var titleArr:[String] = []
    var contentArr:[[MYGMyPatientModel]] = []
    var patientType:Int = 1
    var oldArr:[MYGMyPatientModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        print("abcd"["abcd".startIndex])
        initUI()
        getDatasource()
        NotificationCenter.default.addObserver(self, selector: #selector(screenAction), name: NSNotification.Name.init("patientScreen"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(reloadNewDatasource), name: NSNotification.Name.init("refreshMyPatientList"), object: nil)

    }
    
    @objc func screenAction(obj:Notification){
        let dic:[String:Any] = obj.object as? [String : Any] ?? [:]
        let str:String = dic["screenStr"] as? String ?? ""
        var filteredPeople = oldArr.filter { person in
            person.patient.name.contains(str)
        }
        if str.count == 0{
            filteredPeople = oldArr
        }
        patientArr = [:]
        titleArr.removeAll()
        contentArr.removeAll()
        groupByInitialLetter(people: filteredPeople)
    }
    private func initUI(){
        view.addSubview(patienttableView)
        patienttableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    @objc func reloadNewDatasource(){
        patientArr = [:]
        titleArr.removeAll()
        contentArr.removeAll()
        oldArr.removeAll()
        getDatasource()
    }
    @objc private func getDatasource(){
        MYGNetwork<MYGHomePageAPI, MYGPageModel<MYGMyPatientModel>>.request(target: .getPatientList(param: [
            "type":patientType,
            "pageSize":"100",
            "page":"1"])) {[weak self] item in
                if item.list.count > 0{
                    self?.oldArr = item.list
                    self?.groupByInitialLetter(people: item.list)
                }
                
            } failed: { _, error in
                MMYGHUD.showToast(text: error)
            }
    }
    // 获取字符串的首字母拼音首字母
    //    func getFirstPinyinLetter(_ string: String) -> String {
    //        // 这里只是一个简化的示例，并不考虑多音字等情况
    //        let firstCharacter = string.prefix(1)
    //        let pinyin = firstCharacter.transformToPinYin()?.first // 假设你有一个扩展方法可以得到拼音
    //        return pinyin ?? firstCharacter
    //    }
    func transformToPinYin(str:String)->String{
        let mutableString = NSMutableString(string: str)
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        let string = String(mutableString)
        //        let resultStr:String = string.replacingOccurrences(of: " ", with: "")
        if str.count == 0{
            return "#"
        }
        if string.count == 0{
            let firstCharacter = str.first!
            return String(firstCharacter)
        }else{
            let firstCharacter = string.first!
            return String(firstCharacter)
        }
        // 输出：H
        
    }
    // 将数组按首字母拼音分组
    func groupByInitialLetter(people: [MYGMyPatientModel]){
        var grouped = [String: [MYGMyPatientModel]]()
        
        for person in people {
            let initialLetter = transformToPinYin(str: person.patient.name)
            if grouped[initialLetter] == nil {
                grouped[initialLetter] = []
            }
            grouped[initialLetter]?.append(person)
        }
        var unsortedDictionary: [String: [MYGMyPatientModel]] = [:]
        let sortedDictionary22 = grouped.sorted(by: { $0.key < $1.key })
        for item in sortedDictionary22 {
            unsortedDictionary[item.key] = item.value
            titleArr.append(item.key)
            contentArr.append((item.value))
        }
        patientArr = unsortedDictionary
        patienttableView.reloadData()
    }
    lazy var patienttableView: UITableView = {
        let control = UITableView(frame: CGRectZero, style: .grouped)
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
        control.backgroundColor = .white
        control.register(cellWithClass: MYGPatientTableViewCell.self)
        return control
    }()
    
}
extension MYGPatientListDetailViewController:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return patientArr.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 82.5
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let vi = UIView()
        let lab = UILabel()
        lab.text = titleArr[section]
        lab.font = .regular(19)
        lab.textColor = .rgba(5, 5, 5, 1)
        lab.backgroundColor = .white
        vi.addSubview(lab)
        lab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.height.equalTo(20)
        }
        return vi
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let arr:[MYGMyPatientModel] = contentArr[section]
        return arr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGPatientTableViewCell.self, for: indexPath)
        cell.selectionStyle = .none
        let arr:[MYGMyPatientModel] = contentArr[indexPath.section]
        cell.modelDa = arr[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = MYGPatientDetailViewController()
        let arr:[MYGMyPatientModel] = contentArr[indexPath.section]
        vc.patientModel = arr[indexPath.row]
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension MYGPatientListDetailViewController:JXSegmentedListContainerViewListDelegate {
    
    func listView() -> UIView {
        return view
    }
}
